package com.example.dangerouscargodriver.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.wheelpicker.WheelPickerView;
import com.baiju.style.wheelpicker.bean.WheelItemBean;
import com.baiju.style.wheelpicker.config.WheelPickerConfig;
import com.baiju.style.wheelpicker.listener.OnWheelItemClickListener;
import com.bumptech.glide.Glide;
import com.example.dangerouscargodriver.controller.AttrInfoController;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.UserData;
import com.example.dangerouscargodriver.entry.UserInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class UserInfoActivity extends HttpRequestActivity implements View.OnClickListener {

	private static final String TAG = "UserInfoActivity";
	private ActionBar mActionBar = null;
	private TextView mModifyIcon = null;
	private ImageView mUserIcon = null;
	private EditText mNickName = null;
	private EditText mRealName = null;
	private Button mCommit = null;

	//相册请求码
	private static final int ALBUM_REQUEST_CODE = 1;
	//相机请求码
	private static final int CAMERA_REQUEST_CODE = 2;
	//剪裁请求码
	private static final int CROP_REQUEST_CODE = 3;

	private static final int MODIFY_NICKNAME_REQUEST_CODE = 4;

	//调用照相机返回图片文件
	private File tempFile;

	private TextView mEducation = null;
	private ArrayList<WheelItemBean> mEducationLevelArray;
	private WheelPickerView mEducationLevelPickerView = null;
	private WheelItemBean mEducationBean = null;

	private UserData mUserData = null;

	private String mNewIcon = null;

	private Uri uritempFile = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.initHttpComponent(UserInfoActivity.class);
		setContentView(R.layout.activity_user_info);

		mModifyIcon = findViewById(R.id.btn_modify_icon);
		mModifyIcon.setOnClickListener(this);

		mEducation = findViewById(R.id.ed_education_level);
		mEducation.setOnClickListener(this);

		mUserIcon = findViewById(R.id.img_user_icon);
		mNickName = findViewById(R.id.ed_nick_name);

		mRealName = findViewById(R.id.ed_real_name);

		mActionBar = findViewById(R.id.actionBarUserInfo);
		mActionBar.setOnBackClickListener( new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		initEducationLevelInfo();
		mEducationLevelPickerView = new WheelPickerView();
		mEducationLevelPickerView.init(this, mEducationLevelArray);

		mCommit = findViewById(R.id.btn_action_commit);
		mCommit.setOnClickListener(this);

		executeGetUserDataInfo();
	}

	private void initEducationLevelInfo() {
		mEducationLevelArray = new ArrayList<>();
		WheelItemBean bean0 = new WheelItemBean();
		bean0.setName("初中及以下");
		bean0.setId("0");
		mEducationLevelArray.add(bean0);

		WheelItemBean bean1 = new WheelItemBean();
		bean1.setName("高中");
		bean1.setId("1");
		mEducationLevelArray.add(bean1);

		WheelItemBean bean2 = new WheelItemBean();
		bean2.setName("中专");
		bean2.setId("2");
		mEducationLevelArray.add(bean2);

		WheelItemBean bean3 = new WheelItemBean();
		bean3.setName("大专");
		bean3.setId("3");
		mEducationLevelArray.add(bean3);

		WheelItemBean bean4 = new WheelItemBean();
		bean4.setName("本科");
		bean4.setId("4");
		mEducationLevelArray.add(bean4);

		WheelItemBean bean5 = new WheelItemBean();
		bean5.setName("硕士");
		bean5.setId("5");
		mEducationLevelArray.add(bean5);

		WheelItemBean bean6 = new WheelItemBean();
		bean6.setName("博士");
		bean6.setId("6");
		mEducationLevelArray.add(bean6);

		mEducationBean = bean0;
	}

	private void addEducationLevel(WheelItemBean type) {
		mEducation.setText(type.getName());
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.btn_modify_icon){
			getPicFromAlbm();
		}
		else if(v.getId() == R.id.ed_education_level){
			WheelPickerConfig pickerConfig = new WheelPickerConfig.Builder()
					.title("选择类型")
					.visibleItemsCount(8)
					.defaultItem(mUserData != null ? mUserData.getEducation_background() : mEducationBean.getName())
					.itemCyclic(false)
					.setCustomItemLayout(R.layout.item_city)//自定义item的布局
					.setCustomItemTextViewId(R.id.item_city_name_tv)
					.build();
			pickerConfig.setTitleBackgroundColorStr("#FFD401");

			mEducationLevelPickerView.setConfig(pickerConfig);
			mEducationLevelPickerView.setOnItemClickListener(new OnWheelItemClickListener() {
				@Override
				public void onSelected(WheelItemBean type) {
					if(type != null){
						mEducationBean = type;
						addEducationLevel(type);
					}
				}

				@Override
				public void onCancel() {
					/**/
				}
			});
			mEducationLevelPickerView.showWheelPicker();

		}
		else if(v.getId() == R.id.btn_action_commit){
			executeUpdateUserInfo();
		}
		else{

		}
	}

	/**
	 * 从相册获取图片
	 */
	private void getPicFromAlbm() {
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
	}

	/**
	 * 裁剪图片
	 */
	private void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		//intent.putExtra("return-data", true);
		if (Build.MODEL.contains("MI")) {
			uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
			intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		} else {
			intent.putExtra("return-data", true);
		}

		startActivityForResult(intent, CROP_REQUEST_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (requestCode) {
			case CAMERA_REQUEST_CODE:   //调用相机后返回
				if (resultCode == RESULT_OK) {
					//用相机返回的照片去调用剪裁也需要对Uri进行处理
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						Uri contentUri = FileProvider.getUriForFile(this,
								"com.example.dangerouscargodriver.fileprovider",
								tempFile);
						cropPhoto(contentUri);
					} else {
						cropPhoto(Uri.fromFile(tempFile));
						Log.e("返回图片路径", "" + tempFile);
					}
				}
				break;
			case ALBUM_REQUEST_CODE:    //调用相册后返回
				if (resultCode == RESULT_OK) {
					Uri uri = intent.getData();
					cropPhoto(uri);
					Log.e("我是相册返回", "" + uri);
				}
				break;
			case CROP_REQUEST_CODE:     //调用剪裁后返回
				if (Build.MODEL.contains("MI")) {
					pushFileToRemote(uritempFile.getPath(), RemoteAPICmd.REQUEST_UPLOAD_FILE);
				}
				else{
					Bundle bundle = intent.getExtras();
					if (bundle != null) {
						//在这里获得了剪裁后的Bitmap对象，可以用于上传
						Bitmap image = bundle.getParcelable("data");
						Log.e("我是裁剪后", "" + image);

						//设置到ImageView上
						mUserIcon.setImageBitmap(image);

						//也可以进行一些保存、压缩等操作后上传
						String path = saveImage("crop", image);
						Log.e("我是裁剪后2", "" + path);
						pushFileToRemote(path, RemoteAPICmd.REQUEST_UPLOAD_FILE);
					}
				}

				break;
			case MODIFY_NICKNAME_REQUEST_CODE:
				if (resultCode == RESULT_OK) {
					String newNickName = intent.getStringExtra("NickName");
					mNickName.setText(newNickName);
				}
				break;
		}
	}

	public String saveImage(String name, Bitmap bmp) {
		File appDir = new File(Environment.getExternalStorageDirectory().getPath());
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = name + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			return file.getAbsolutePath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void pushFileToRemote(String file, int action){
		HashMap<String, String> header = new HashMap<>();
		header.put("token", AuthController.Instance().getToken());
		HashMap<String, String> param = new HashMap<>();
		param.put("water", "1");

		sendHttpMultipartRequest(RemoteAPI.REQUEST_UPLOAD_FILE,
				header,
				param,
				file,
				action);
	}

	private void executeUpdateUserInfo(){
		HashMap<String, String> header = new HashMap<String, String>();
		header.put("token", AuthController.Instance().getToken());

		HashMap<String, String> param = new HashMap<String, String>();
		param.put("head_pic", mNewIcon == null ? mUserData.getHead_pic() : mNewIcon);
		param.put("username", mNickName.getText().toString());
		param.put("realname", mRealName.getText().toString());
		param.put("education_background", mEducation.getText().toString());
		//param.put("business", mUserData.getBusiness());
		//param.put("profession", mUserData.getProfession());

		sendHttpRequest(IHttpRequest.RequestMethod.PUT_METHOD,
				RemoteAPI.REQUEST_V1_UPDATE_USER_DATA,
				header,
				param,
				RemoteAPICmd.REQUEST_V1_UPDATE_USER_DATA);
	}

	private void executeGetUserDataInfo(){
		HashMap<String, String> header = new HashMap<String, String>();
		header.put("token", AuthController.Instance().getToken());

		sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
				RemoteAPI.REQUEST_V1_UPDATE_USER_DATA_EDIT,
				header,
				null,
				RemoteAPICmd.REQUEST_V1_UPDATE_USER_DATA_EDIT);
	}

	private void refreshUserData(){
		if(mUserData != null){
			mNickName.setText(mUserData.getUsername());
			mUserIcon.setImageURI(Uri.parse(mUserData.getHead_pic()));
			if(mUserData.getRealname() != null){
				mRealName.setText(mUserData.getRealname());
			}
			Glide.with(this).load(mUserData.getHead_pic()).into(mUserIcon);
			mEducation.setText(mUserData.getEducation_background());
		}
	}

	@Override
	protected void onHttpResponse(int actionId, String response) {
		try {
			JSONObject res = new JSONObject(response);
			Gson gson = new Gson();
			if(actionId == RemoteAPICmd.REQUEST_V1_UPDATE_USER_DATA){
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					ToastUtils.showLongToast(this, "提交成功");
					UserInfoController.Instance().updateUserInfo();
					finish();
				}
				else{
					ToastUtils.showLongToast(this, "提交失败");
				}
			}
			if(actionId == RemoteAPICmd.REQUEST_V1_UPDATE_USER_DATA_EDIT){
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					mUserData = gson.fromJson(res.getString("data"), UserData.class);
					if(mUserData != null){
						refreshUserData();
					}
				}
				else{

				}
			}
			else if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE){
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1) {
					mNewIcon = res.getJSONObject("data").getString("url");
					Glide.with(this).load(mNewIcon).into(mUserIcon);
				}
			}
			else{

			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onHttpErrorResponse(int actionId, String response) {

	}
}